<template>
  <div v-loading="loading">
    <el-card>
      <el-col>
        <el-button size="small" type="primary" @click="dataFormSubmitHandle()">{{ $t('save') }}</el-button>
        <el-button size="small" @click="closeTab()">{{ $t('close') }}</el-button>
      </el-col>
      <el-col :span="24" class="form_parent">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :label-width="$i18n.locale === 'en-US' ? '120px' : '80px'">
          <el-col :span="12">
            <!-- 表名称 -->
            <el-form-item label="表名称" prop="tableName">
              <!--文本框-->
              <el-input v-model="dataForm.tableName" placeholder="表名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 表备注 -->
            <el-form-item label="表备注" prop="tableComment">
              <!--文本框-->
              <el-input v-model="dataForm.tableComment" placeholder="表备注" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 规则表外键 -->
            <el-form-item label="规则" prop="ruleId">
              <!--下拉框-->
              <el-select v-model="dataForm.ruleId" placeholder="规则" clearable style="width:100%" @change="ruleChangeEvent">
                <el-option v-for="template in ruleList" :key="template.id" :label="template.ruleName" :value="template.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- 执行建表SQL -->
          <el-col :span="12">
            <el-form-item label="表操作">
              <vxe-tooltip content="强制：不保留数据，删表重建！" enterable>
                <el-checkbox v-model="dataForm.forceFlag">强制</el-checkbox>
              </vxe-tooltip>
              <vxe-tooltip content="立即：保存时立即更新表结构，此标记不保留！" enterable>
                <el-checkbox v-model="dataForm.immeFlag">立即</el-checkbox>
              </vxe-tooltip>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="更新" prop="isUpdate">
              <el-switch v-model="dataForm.isUpdate">
              </el-switch>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <!-- 备注说明 -->
            <el-form-item label="备注说明" prop="remark">
              <!--文本域-->
              <el-input type="textarea" :rows="3" v-model="dataForm.remark" placeholder="备注说明"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-col>
    </el-card>
    <child-list ref="childList"></child-list>
  </div>
</template>

<script>
import debounce from 'lodash/debounce'
import mainContent from '@/views/main-content'
import ChildList from './dpdTableColumns-child'
import mixinDpdCommonJs from './common/dpd-common'
var content = mainContent

export default {
  mixins: [mixinDpdCommonJs],
  data () {
    return {
      timestamp: this.$route.params.timestamp,
      loading: false,
      activeName: '1',
      ruleList: [],
      showHelpTip1: false,
      dataForm: {
        children: [],
        deltList: [],
        id: this.$route.params.id,
        tableName: '',
        tableComment: '',
        isUpdate: true,
        forceFlag: false,
        immeFlag: false,
        ruleId: '',
        ruleClass: '',
        dbType: '',
        remark: '',
        creator: '',
        createDate: '',
        updater: '',
        updateDate: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        tableName: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        tableComment: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        isUpdate: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        ruleId: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getRuleList()
  },
  activated () {
    // 通过路由参数pid, 控制列表请求操作
    if (this.$route.params.timestamp !== this.timestamp) {
      this.$refs['dataForm'].resetFields()
    }
    if (this.$route.params.id) {
      this.dataForm.id = this.$route.params.id
      this.loading = true
      this.getInfo()
    }
  },
  components: {
    ChildList
  },
  methods: {
    ruleChangeEvent (val) {
      let outRow = this.$getDataItem(this.ruleList, val, 'id')
      this.dataForm.ruleClass = outRow.ruleClass
      this.dataForm.dbType = outRow.dbType
      this.refreshFieldTypeList()
    },
    async refreshFieldTypeList () {
      this.$refs.childList.dbType = this.dataForm.dbType
      await this.$refs.childList.getFieldTypeList()
    },
    // 刷新子列表
    async refreshChildList () {
      if (this.dataForm.id) {
        this.$refs.childList.dataForm.tableId = this.dataForm.id
        await this.refreshFieldTypeList()
        this.$refs.childList.getDataList().then(() => {
          this.$refs.childList.rowDrop()
        })
      }
    },
    getRuleList () {
      this.$http.get('/dpd/dpdRule/list').then(({ data: res }) => {
        if (res.code !== 0) {
          return
        }
        this.ruleList = res.data
      })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/dpd/dpdTable/${this.dataForm.id}`).then(({ data: res }) => {
        this.loading = false
        if (res.code !== 0) {
          return false
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.refreshChildList()
      }).catch(() => { })
    },
    // 关闭 tab
    closeTab () {
      content.methods.tabRemoveHandle(this.$route.name)
      this.$emit('refreshDataList')
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: this.$t('prompt.valid'),
            type: 'error',
            duration: 1500
          })
          return false
        }
        let child = this.$refs.childList
        if (child.getAllData().length <= 0) {
          this.$message({
            message: this.$t('prompt.children'),
            type: 'error',
            duration: 500
          })
          return false
        }
        // 子表验证
        child.fullValidEvent().then(res => {
          if (!res) return
          let addFlag = !this.dataForm.id
          this.dataForm.children = child.getAllData()
          this.dataForm.deltList = child.deltList
          this.$http[!this.dataForm.id ? 'post' : 'put']('/dpd/dpdTable/', this.dataForm).then(({ data: res }) => {
            if (res.code !== 0) {
              return false
            }
            if (this.dataForm.immeFlag) {
              this.createSQL(this.dataForm)
            }
            this.$message({
              message: this.$t('prompt.success'),
              type: 'success',
              duration: 500,
              onClose: () => {
                let formFlag = this.$route.params.formFlag
                if (formFlag && addFlag) {
                  let data = {
                    id: this.$route.params.formId,
                    modelId: res.data.id,
                    modelCode: res.data.tableName,
                    modelFlag: true
                  }
                  this.drsForm(data)
                }
                this.closeTab()
              }
            })
          })
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    /**
     * 联动设计表单
     */
    drsForm (data) {
      this.$http.put('/drs/drsFormDef/', data).then(({ data: res }) => { })
    }
  }
}
</script>
